<script>
import FileUpload from "@/components/common/FileUpload.vue";
import http from "@/api/httpRequest";
import ModifyPasswordDialog from "@/components/setting/ModifyPasswordDialog.vue";
import {Dialog} from "vant";

export default {
  name: "Profile",
  components: {ModifyPasswordDialog, FileUpload},
  data() {
    return {
      showPopup: false,
      formValue: {},
      // current user
      userInfo: {},
      maxSize: 5 * 1024 * 1024,
      action: "/image/upload",
      modifyPwdVisible: false,
    }
  },
  watch: {},
  computed: {
    imageAction() {
      return `/image/upload`;
    }
  },
  methods: {
    showModifyPwd() {
      this.modifyPwdVisible = true
    },
    async handleModifyPwd(formData) {
      try {
        console.log("formData", formData)
        await this.$http.post('/modifyPwd', formData)
        this.modifyPwdVisible = false
        this.$wsApi.close(3000)
        Dialog.alert({
          title: 'Password changed successfully',
          message: 'Please log in again.',
          confirmButtonColor: 'var(--chat-theme-color)',
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
        }).then(() => {
          location.href = "/";
        });
      } catch (error) {
        this.$message.error('Password change failed:', error.response?.data?.message)
      }
    },
    async getCurrentUser() {
      await http({
        url: '/user/self',
        method: 'POST' // GET or POST
      }).then((userInfo) => {
        console.log('userInfo', userInfo)
        this.$data.userInfo = JSON.parse(JSON.stringify(userInfo));
        this.$data.formValue = JSON.parse(JSON.stringify(userInfo));
        console.log('Current user: ', this.$data.userInfo)
      }).catch(() => {
      });
    },
    onSubmit(values) {
      console.log('submit', this.$data.formValue);
      this.$http({
        url: "/user/update",
        method: "POST",
        data: this.$data.formValue
      }).then(() => {
        this.$store.commit("setUserInfo", this.$data.formValue);
        this.getCurrentUser()
        this.$data.showPopup = false
        this.$message.success("Modified successfully");
      })
    },
    onShowPopup() {
      this.$data.showPopup = true
    },
    onExit() {
      this.$wsApi.close(3000);
      sessionStorage.removeItem("accessToken");
      location.href = "/";
    },
    onUploadSuccess(data, file) {
      this.$data.userInfo.headImage = data.originUrl;
      this.$data.formValue.headImage = data.originUrl;
      this.$data.userInfo.headImageThumb = data.thumbUrl;
      this.$data.formValue.headImageThumb = data.thumbUrl;
      this.$store.commit("setUserInfo", this.$data.userInfo);
      this.onSubmit()
    }
  },
  mounted() {
    this.getCurrentUser()
    console.log('this.$store.state.userStore.userInfo', this.$store.state.userStore.userInfo)
  }
}
</script>

<template>
  <div class="profile-container">
    <div class="user-avatar">
      <file-upload class="avatar-uploader avatar" :action="imageAction" :showLoading="true" :maxSize="maxSize"
                   :encrypted="false"
                   @success="onUploadSuccess" :fileTypes="['image/jpeg', 'image/png', 'image/jpg', 'image/webp']">
        <img v-if="userInfo.headImage" :src="userInfo.headImage" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <div class="avatar-edit"><img class="" src="../assets/image/all/profile-avatar-edit-icon.png" alt=""></div>
      </file-upload>
      <div class="username-text">{{ userInfo.userName }}</div>
    </div>
    <div class="user-message">
      <div class="message-row nickname-text">
        <div class="title">Nickname:</div>
        <div class="text">{{ userInfo.nickName }}</div>
      </div>
      <div class="message-row gender-text">
        <div class="title">Gender:</div>
        <div class="text">{{ userInfo.sex === 0 ? 'Male' : 'Female' }}</div>
      </div>
      <div class="message-row signature-text" v-if="false">
        <div class="title">Signature:</div>
        <!--        <div class="text" v-if="!userInfo.signature">null</div>-->
        <div class="text">{{ userInfo.signature ? userInfo.signature : 'null' }}</div>
      </div>
      <!--      <div class="message-row text" v-if="userInfo.signature">{{ userInfo.signature }}</div>-->
    </div>
    <div class="option-btn">
      <div class="edit-profile" @click="onShowPopup"><img src="../assets/image/all/profile-edit-btn.png" alt="">
      </div>
      <div class="password-btn">
        <el-button style="width: 100%;height: 100%" type="danger" @click="showModifyPwd">
          <div class="button-content">
            <div><img class="img-icon" src="../assets/image/all/profile-edit-icon.png" alt=""></div>
            <div class="ml-10">Change password</div>
          </div>
        </el-button>
      </div>
<!--      <div class="logout-btn">-->
<!--        <el-button style="width: 100%;height: 100%" @click="onExit" type="danger" plain>-->
<!--          <div class="button-content">-->
<!--            <div><img class="img-icon" src="../assets/image/all/profile-logout-icon.png" alt=""></div>-->
<!--            <div class="ml-10">Logout</div>-->
<!--          </div>-->
<!--        </el-button>-->
<!--      </div>-->
      <div class="logout-btn" @click="onExit"><img src="../assets/image/all/profile-logout-btn.png" alt=""></div>
    </div>
    <van-popup :value="showPopup" position="bottom" class="profile-popup" close-on-click-overlay>
      <div class="profile-popup-content">
        <div class="title">Edit Profile</div>
        <div class="profile-form">
          <van-form @submit="onSubmit" ref="userInfoForm">
            <div class="profile-form-item" v-if="formValue">
              <div class="label">Username</div>
              <van-field
                  disabled
                  class="label-field"
                  v-model="formValue.userName"
                  name="username"
                  label=""
                  placeholder="Username"
                  border
              />
            </div>
            <div class="profile-form-item">
              <div class="label">Nickname</div>
              <van-field
                  class="label-field"
                  v-model="formValue.nickName"
                  name="nickname"
                  label=""
                  placeholder="Nickname"
                  border
              />
            </div>
            <div class="profile-form-item">
              <div class="label">Gender</div>
              <van-radio-group v-model="formValue.sex" direction="horizontal" class="label-radio">
                <van-radio :name="0">Male</van-radio>
                <van-radio :name="1">Female</van-radio>
              </van-radio-group>
            </div>
            <div class="profile-form-item" v-if="false">
              <div class="label">Signature</div>
              <van-field
                  class="label-field"
                  v-model="formValue.signature"
                  name="signature"
                  rows="2"
                  type="textarea"
                  label=""
                  placeholder="Signature"
                  border
              />
            </div>
            <div class="profile-btn-group">
              <div class="profile-cancel-btn" @click="showPopup = false">
                <img class="" src="../assets/image/all/profile-cancel-btn.png" alt="">
              </div>
              <div class="profile-save-btn" @click="onSubmit">
                <img class="" src="../assets/image/all/profile-save-btn.png" alt="">
              </div>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>
    <modify-password-dialog v-model="modifyPwdVisible" @submit="handleModifyPwd"/>
  </div>
</template>

<style scoped lang="scss">
::v-deep .v-modal {
  background: transparent !important;
}

.avatar-uploader {
  position: relative;
  width: 160px;
  height: 160px;
  border-radius: 50%;
  background: var(--slot-color);

  ::v-deep .el-upload {
    position: absolute;
    border-radius: 6px;
    cursor: pointer;
    width: 160px;
    height: 160px;
    display: flex !important;
    justify-content: center;
    align-items: center;
  }

  .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 24px;
    color: #8c939d;
    line-height: var(--width);
    text-align: center;
    display: flex !important;
    justify-content: center;
    align-items: center;
  }

  .avatar {
    width: var(--width);
    height: var(--width);
    display: block;
  }
}

.profile-popup {
  width: 100%;
  z-index: 99999999999;
  transform: translate(0, -110px);
}

.profile-popup-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10px 24px;
  z-index: 9999;
  max-height: 550px;
  overflow-y: auto;

  .title {
    display: flex;
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 0;
    line-height: 22.4px;
    color: rgba(41, 41, 41, 1);
    text-align: center;
    margin-bottom: 17px;
  }

  .profile-form .van-form {
    height: 100% !important;
  }

  .profile-form {
    width: 100%;
    //height: 450px;
    //overflow-y: auto;
    display: flex;
    margin-bottom: 70px;

    .van-form {
      width: 100%;
    }

    .profile-form-item {
      margin-top: 16px;

      .label {
        font-size: 14px;
        font-weight: 400;
        letter-spacing: 0;
        line-height: 16.41px;
        color: rgba(104, 106, 138, 1);
        margin-bottom: 8px;
      }

      .van-field--disabled {
        background: var(--slot-color);
      }

      .label-field {
        border-radius: 8px;
        border: 1px solid rgba(208, 209, 219, 1);
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }

      .label-radio {
      }
    }
  }

  .profile-btn-group {
    display: flex;
    gap: 20px;
    justify-content: space-between;
    align-items: center;
    height: 60px;
    margin-top: 30px;

    .profile-cancel-btn, .profile-save-btn {
      flex: 1;
      height: 100%;
      border-radius: 30px;
      //background: var(--slot-color);
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.profile-container {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  padding: 32px 24px;
  display: flex;
  flex-direction: column;
  align-items: center;

  .user-avatar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .avatar {
      position: relative;
      width: 160px;
      height: 160px;
      border-radius: 50%;
      background: var(--slot-color);

      .avatar-edit {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: var(--slot-color);
        position: absolute;
        right: 0;
        top: 0;
      }
    }

    .username-text {
      margin-top: 32px;
      font-size: 22px;
      font-weight: 400;
      letter-spacing: 0;
      color: rgba(44, 45, 58, 1);
      margin-bottom: 16px;
    }
  }

  .user-message {
    width: 100%;

    .message-row {
      display: flex;
      justify-content: flex-start;
      margin-bottom: 16px;

      .text {
        word-break: break-all;
        white-space: normal;
      }
    }

    .title {
      display: flex;
      font-size: 18px;
      font-weight: 400;
      letter-spacing: 0;
      line-height: 21.1px;
      color: rgba(104, 106, 138, 1);
      margin-right: 10px;
    }

    .text {
      display: flex;
      font-size: 18px;
      font-weight: 400;
      letter-spacing: 0;
      line-height: 21.1px;
      color: rgba(44, 45, 58, 1);
    }
  }

  .option-btn {
    width: 100%;

    .button-content {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .el-button .img-icon {
      width: 25px;
      height: 25px;
    }

    .logout-btn .el-button  .img-icon {
      width: 20px;
      height: 20px;
    }

    .edit-profile, .logout-btn, .password-btn {
      width: 100%;
      height: 56px;
      margin-top: 10px;

      img {
        width: 100%;
        height: 100%;
        //object-fit: contain;
      }
    }
  }
}
</style>